<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联的成果ID" prop="outcomeId">
        <el-input
          v-model="queryParams.outcomeId"
          placeholder="请输入关联的成果ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="奖项名称" prop="awardName">
        <el-input
          v-model="queryParams.awardName"
          placeholder="请输入奖项名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="颁奖机构" prop="awardOrganization">
        <el-input
          v-model="queryParams.awardOrganization"
          placeholder="请输入颁奖机构"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="奖项颁发日期" prop="awardDate">
        <el-date-picker clearable
          v-model="queryParams.awardDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择奖项颁发日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['outcome:award:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['outcome:award:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['outcome:award:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['outcome:award:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="awardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="奖励ID" align="center" prop="awardId" />
      <!-- <el-table-column label="成果ID" align="center" prop="outcomeId" /> -->
      <el-table-column label="奖项名称" align="center" prop="awardName" />
      <el-table-column label="颁奖机构" align="center" prop="awardOrganization" />
      <el-table-column label="奖项颁发日期" align="center" prop="awardDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.awardDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="奖项描述" align="center" prop="awardDescription" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['outcome:award:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['outcome:award:remove']"
          >删除</el-button>
          <el-button
           size="mini"
           type="text"
           icon="el-icon-document"
           @click="fetchAwardTrackData(scope.row.awardId)"
         >查看变更记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="追踪记录" :visible.sync="trackDialogVisible" width="800px" append-to-body>
      <el-table :data="trackList" size="small" v-loading="trackLoading" @selection-change="handleSelectionChanges">
        <el-table-column type="selection" width="55" align="center" />
    <el-table-column prop="trackId" label="记录ID" align="center" />
    <el-table-column prop="actionType" label="操作类型" align="center">
      <template slot-scope="scope">
        <el-tag type="info" v-if="scope.row.actionType === 'add'">新增</el-tag>
        <el-tag type="success" v-else-if="scope.row.actionType === 'update'">修改</el-tag>
        <el-tag type="danger" v-else>删除</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="奖励ID" align="center" prop="awardId" />
    <!-- <el-table-column label="成果ID" align="center" prop="outcomeId" /> -->
    <el-table-column label="奖项名称" align="center" prop="awardName" />
    <el-table-column label="颁奖机构" align="center" prop="awardOrganization" />
      <el-table-column label="奖项颁发日期" align="center" prop="awardDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.awardDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="奖项描述" align="center" prop="awardDescription" />
    <el-table-column prop="createdBy" label="创建人" align="center" />
    <el-table-column prop="createdAt" label="创建时间" align="center" />
    <el-table-column prop="updatedAt" label="更新时间" align="center" />
    <el-table-column prop="updatedBy" label="更新人" align="center" />
    <el-table-column prop="deletedAt" label="删除时间" align="center" />
    <el-table-column prop="deleteFlag" label="删除标记" align="center">
      <template slot-scope="scope">
        <el-tag type="info" v-if="scope.row.deleteFlag === 0">否</el-tag>
        <el-tag type="danger" v-else>是</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="version" label="版本号" align="center" />

  </el-table>
  <div slot="footer" class="dialog-footer">
    <el-button @click="trackDialogVisible = false">关闭</el-button>
    <el-button type="primary" @click="revertToSelectedRecord">回溯到此记录</el-button>
</div>
</el-dialog>




    <!-- 添加或修改科研奖励管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联的成果ID" prop="outcomeId">
          <el-input v-model="form.outcomeId" placeholder="请输入关联的成果ID" />
        </el-form-item>
        <el-form-item label="奖项名称" prop="awardName">
          <el-input v-model="form.awardName" placeholder="请输入奖项名称" />
        </el-form-item>
        <el-form-item label="颁奖机构" prop="awardOrganization">
          <el-input v-model="form.awardOrganization" placeholder="请输入颁奖机构" />
        </el-form-item>
        <el-form-item label="奖项颁发日期" prop="awardDate">
          <el-date-picker clearable
            v-model="form.awardDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择奖项颁发日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="奖项描述" prop="awardDescription">
          <el-input v-model="form.awardDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAward, getAward, delAward, addAward, updateAward,getAwardTrack } from "@/api/outcome/award";

export default {
  name: "Award",
  data() {
    return {
      selectedTrack: null, // 存储选中的追踪记录
         // 追踪记录弹窗控制
      trackDialogVisible: false,
     // 追踪记录数据
      trackList: [],
      // 追踪记录加载状态
      trackLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科研奖励管理表格数据
      awardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        outcomeId: null,
        awardName: null,
        awardOrganization: null,
        awardDate: null,
        awardDescription: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // outcomeId: [
        //   { required: true, message: "关联的成果ID不能为空", trigger: "blur" }
        // ],
        awardName: [
          { required: true, message: "奖项名称不能为空", trigger: "blur" }
        ],
        awardOrganization: [
          { required: true, message: "颁奖机构不能为空", trigger: "blur" }
        ],
        awardDate: [
          { required: true, message: "奖项颁发日期不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询科研奖励管理列表 */
    getList() {
      this.loading = true;
      listAward(this.queryParams).then(response => {
        this.awardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        awardId: null,
        outcomeId: null,
        awardName: null,
        awardOrganization: null,
        awardDate: null,
        awardDescription: null,
        createdBy: null,
        updatedBy: null,
        deletedBy: null,
        deletedAt: null,
        isDeleted: null,
        version: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.awardId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加科研奖励管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const awardId = row.awardId || this.ids
      getAward(awardId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改科研奖励管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.awardId != null) {
            updateAward(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAward(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const awardIds = row.awardId || this.ids;
      this.$modal.confirm('是否确认删除科研奖励管理编号为"' + awardIds + '"的数据项？').then(function() {
        return delAward(awardIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('outcome/award/export', {
        ...this.queryParams
      }, `award_${new Date().getTime()}.xlsx`)
    },

    fetchAwardTrackData(awardId)
    {
    console.log("Fetching data for awardId:", awardId);
    this.trackDialogVisible = true; // 显示对话框
    this.trackList = []; // 清空之前的数据
    this.trackLoading = true; // 显示加载状态
    getAwardTrack(awardId) // 调用 API 获取数据
        .then(response => {
            console.log("Response data:", JSON.stringify(response.data, null, 2));
            this.trackList = response.data || []; // 设置追踪数据
        })
        .catch(error => {
            this.$message.error('获取追踪记录失败');
            console.error(error);
        })
        .finally(() => {
            this.trackLoading = false; // 隐藏加载状态
        });
    },
    handleSelectionChanges(selection) {
        this.selectedTrack = selection.length > 0 ? selection[0] : null; // 选择第一条记录
    },
    revertToSelectedRecord() {
        if (!this.selectedTrack) {
            this.$message.warning('请先选择一条记录进行回溯');
            return;
        }
        // 这里可以实现回溯逻辑，比如调用 API 更新原表数据
        const updatedData = {
            // 根据 selectedTrack 的内容构建更新的数据
            ...this.selectedTrack,
            // 例如，您可能想要清除一些字段或者修改某些字段
        };
        updateAward(updatedData) // 假设这是更新原表的 API
            .then(response => {
                this.$message.success('数据回溯成功');
                // 可能需要重新获取原表数据
                this.getList();
            })
            .catch(error => {
                this.$message.error('数据回溯失败');
                console.error(error);
            });
    }


  }
};
</script>
